<template>
    <div>
        <div><h1>商品类型</h1></div>
        <div>
            <el-button type="primary" @click="handleAdd">添加类型</el-button>
        </div>
        <div>
            <el-table
                :data="typeTree"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
            >
                <el-table-column prop="name" label="名称" sortable />
                <el-table-column prop="typeStatus" label="状态">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <el-tag
                                type="success"
                                v-if="scope.row.typeStatus == 0"
                                >显示</el-tag
                            >
                            <el-tag
                                type="danger"
                                v-if="scope.row.typeStatus == 1"
                                >隐藏</el-tag
                            >
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="typeTop" label="排序" />
                <el-table-column prop="createTime" label="创建时间" />
                <el-table-column label="类型图片">
                    <template #default="scope">
                        <el-image v-if="scope.row.typeImage!=null" :src="scope.row.typeImage" style="width: 50px; height: 50px"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button
                            size="small"
                            type="danger"
                            @click="handleDelete(scope.row)"
                        >
                            删除
                        </el-button>
                        <el-button
                            size="small"
                            type="primary"
                            v-if="scope.row.typeStatus == 0"
                            @click="handleChange(scope.row, 1)"
                        >
                            隐藏
                        </el-button>
                        <el-button
                            size="small"
                            type="success"
                            v-if="scope.row.typeStatus == 1"
                            @click="handleChange(scope.row, 0)"
                        >
                            显示
                        </el-button>

                        <el-button
                            size="small"
                            type="success"
                            @click="onAddType(scope.row)"
                        >
                            添加
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <el-dialog
                v-model="dialogFormVisible"
                :title="title"
                width="500"
            >
                <el-form :model="form">
                    <el-form-item
                        label="分类名称"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.typeName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="分类图片"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            class="avatar-uploader"
                            action="http://localhost:10010/shop/type/uploadFile"
                            :show-file-list="false"
                            :headers="headers"
                            :on-success="handleAvatarSuccess"
                        >
                            <img
                                v-if="imageUrl"
                                :src="imageUrl"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon"
                                ><Plus
                            /></el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item
                        label="分类排序"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.typeTop" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth">
                        <el-radio-group v-model="form.typeStatus">
                            <el-radio :value="0">显示</el-radio>
                            <el-radio :value="1">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >取消</el-button
                        >
                        <el-button
                            type="primary"
                            v-if="title == '添加类型'"
                            @click="onSubmitAddType"
                        >
                            确认
                        </el-button>
                        <el-button
                            type="primary"
                            v-if="title != '添加类型'"
                            @click="onSubmitEditType"
                        >
                            修改
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { getTypeTree, setTypeStatus, deleteTypeById, addType, updateType } from "@/api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";

import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { title } from "process";

const imageUrl = ref('')

const typeTree = ref([]);

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
    typePid: 0,
    typeName: null,
    typeStatus: 0,
    typeTop: 0,
    typeImage: null,
});
const title = ref('添加类型');

const headers = {
    token: sessionStorage.getItem('token')
}

// 修改商品类型
const onSubmitEditType = () => {
    form.value.typeImage = imageUrl.value;
    updateType(form.value).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("修改成功");
            loadTypeTree();
            dialogFormVisible.value = false;
        } else {
            ElMessage.error(res.data.msg);
        }
    });
}

const resetForm = () => {
    form.value = {
        typePid: 0,
        typeId: null,
        typeName: null,
        typeStatus: 0,
        typeTop: 0,
        typeImage: null,
    };
    imageUrl.value = '';
};

// 添加子类型
const onAddType = (row: any) => {
    console.log(row);
    resetForm();
    title.value = '添加类型';
    form.value.typePid = row.id;
    dialogFormVisible.value = true;
}

// 添加类型
const onSubmitAddType = () => {
    addType(form.value).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("添加成功");
            loadTypeTree();
            dialogFormVisible.value = false;
        }
        else {
            ElMessage.error(res.data.msg);
        }
    })
}

// 图片上传成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  // 回显图片
  imageUrl.value = response.data;
  // 把图片地址赋值给表单，用于添加
  form.value.typeImage = imageUrl.value;
  console.log('handleAvatarSuccess', imageUrl.value);
  
}

// 显示添加类型对话框
const handleAdd = () => {
    // 添加一级分类
    form.value.typePid = 0;
    title.value = '添加类型';
    dialogFormVisible.value = true;
};

// 状态切换
const handleChange = (row: any, status: any) => {
    setTypeStatus(row.id, status).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("修改成功");
            loadTypeTree();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 编辑类型
const handleEdit = (row: any) => {
    console.log(row);
    title.value = '编辑类型';
    Object.assign(form.value, row);
    form.value.typeName = row.name;
    form.value.typeId = row.id;
    form.value.typePid = row.parentId;
    imageUrl.value = row.typeImage;
    dialogFormVisible.value = true;
};
const handleDelete = (row: any) => {
    console.log(row);
    ElMessageBox.confirm("删除数据以后，无法恢复，您确认要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "放弃",
        type: "warning",
    })
        .then(() => {
            // 确认删除
            deleteTypeById(row.id).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success("删除成功");
                    loadTypeTree();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        })
        .catch(() => {
            // 取消删除
        });
};

// 获取商品类型树
const loadTypeTree = () => {
    getTypeTree().then((res) => {
        console.log("typeTree", res);

        if (res.data.code == 200) {
            typeTree.value = res.data.data;
        }
    });
};

// 页面钩子函数
onMounted(() => {
    loadTypeTree();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
